'use strict';

import {
  appConst,
} from './instances';
/**
 * @class RokidApp
 */
class AppMain {
  /**
   * @method constructor
   * @param {Object} event
   * @param {Object} context
   * @param {Object} callback
   */
  constructor() {
    this._event = null;
    this._context = null;
    this._callback = null;
    this._rokid = null;

    // TODO: 暂未使用
    // 流程阶段: 0进行中，1结束，2已经提交结束
    this._stage = appConst.STAGEINIT;

    this._executants = {};
    this._ttsStrArr = []; // 本次请求的tts内容
    // this._utils = new AppUtils();
    // this._session = new AppSession();
    // this._data = new AppData(this);
  }

  init(event, context, callback) {
    if (event && context && callback) {
      this._event = event;
      this._context = context;
      this._callback = callback;
      this._rokid = Rokid.handler(event, context, callback);
      if (appConst.debug) {
        console.debug('[AppMain]', 'Rokid init success.');
      }
    }
  }

  // 加载并注册 handers
  registerHandlers(executants) {
    let self = this;
    this._executants = Object.assign(this._executants, executants);
    if (appConst.debug) {
      for (const key in this._executants) {
        if (this._executants.hasOwnProperty(key)) {
          console.debug('[RegHandler]', key, 'has added.');
        }
      }
    }

    let handlers = {};
    for (const key in this._executants) {
      if (this._executants.hasOwnProperty(key)) {
        handlers[key] = function () {
          let holder = this;
          self.go(holder, key);
        }
      }
    }

    this._rokid.registerHandlers(handlers);
  }

  // 启动 Rokid
  execute() {
    this._rokid.execute();
  }

  // 获取用户 ID
  getUserID() {
    let userID = Rokid.param.context.user.userId;
    if (!userID) {
      userID = 'test_user_id';
    }
    return userID;
  }

  // 设置 tts, 会清空之前已经添加的 tts
  setTtsStr(str) {
    this._ttsStrArr = [str];
  }

  // 追加 tts
  addTtsStr(str) {
    this._ttsStrArr.push(str);
  }

  // 获取 tts
  getTtsStr(str) {
    let res = this._ttsStrArr.join('');
    if (str) {
      res += str;
    }
    return res;
  }

  // yes or no 问答确认
  YON(intent) {
    let acts = ['是的', '取消'];
    return {
      confirmIntent: intent,
      confirmSlot: 'yes_or_no',
      optionWords: ['是的', '取消'],
      retryTts: appConst.tpls.retryWithActionTips.format({
        'action': acts.join('、')
      })
    }
  }

  // TODO: 暂未使用
  emit(holder, action, msg) {
    holder.emit(action, msg);
  }

  // hander 执行调度
  go(holder, handleName) {
    let self = this;
    let handle = null;
    console.debug('[GoStart]', handleName);
    if (self._executants.hasOwnProperty(handleName)) {
      handle = self._executants[handleName];
    }
    if (handle !== null) {
      self._session.setHolder(holder);
      self._data.reload((err) => {
        console.debug('[GoExec]', handleName);
        handle(holder);
        self._session.submit();
        console.debug('[GoEnd]', handleName);
        //保存数据
        self._data.submit((err) => {
          holder.emit(':done');
        });
      });
    } else {
      holder.emit(':error', 'can not get executant');
      return;
    }
  }
}

export default AppMain;
